package domain;

public class TimeInterval {
	public TimeInterval(long begin, long end) {
		if(begin < 0 || end < -1) throw new IllegalArgumentException("Negative Time when creating time interval");
		if(end < begin && end != -1) throw new IllegalArgumentException("time interval ends before it begins");
		setStartTime(begin);
		setEndTime(end);
	}
	
	//constructor voor halfopen interval (tot tijd oneindig)
	public TimeInterval(long begin) {
		setStartTime(begin);
		endTime = -1;
	}
	
	public boolean contains(long time) {
		if(endTime == -1) return time >= startTime;
		return time <= getEndTime() && time >= getStartTime();
	}
	
	//geeft doorsnede tussen twee intervals terug, null als deze leeg is
	public TimeInterval getOverlapWith(TimeInterval other) {
		long s = Math.max(getStartTime(),other.getStartTime());
		long e;

		if(isOpenEnded() && other.isOpenEnded()) {
			return new TimeInterval(s,-1);
		} else if(isOpenEnded()) {
			e = other.getEndTime();
		} else if(other.isOpenEnded()) {
			e = getEndTime();
		} else {
			e = Math.min(getEndTime(), other.getEndTime());
		}
		
		if(s <= e) return new TimeInterval(s,e);
		else return null;
	}
	
	private void setStartTime(long startTime) {
		this.startTime = startTime;
	}
	public long getStartTime() {
		return startTime;
	}

	private void setEndTime(long endTime) {
		this.endTime = endTime;
	}

	public long getEndTime() {
		return endTime;
	}
	
	public boolean isOpenEnded() {
		return endTime == -1;
	}
	
	@Override
	public String toString() {
		return "["+ getStartTime() + "," + getEndTime() +"]";
	}

	private long startTime;
	private long endTime; //-1 voor oneindig
	
	//creëert nieuw tijdsinterval gelijk aan huidige opgeschoven met i
	public TimeInterval shift(long i) {
		if(isOpenEnded()) {
			return new TimeInterval(getStartTime()+i);
		} else {
			return new TimeInterval(getStartTime()+i, getEndTime()+i);
		}
	}
}
